from PIL import Image
import os
import glob

def convert_jpg_to_bmp(input_folder, output_folder, target_size):
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    for jpgfile in glob.glob(os.path.join(input_folder, "*.jpg")):
        image = Image.open(jpgfile)

        # 缩放图像到目标尺寸，保持纵横比
        image.thumbnail(target_size, Image.ANTIALIAS)

        # 创建一个新的512x512黑色背景图像
        new_image = Image.new('RGB', target_size, (0, 0, 0))

        # 计算图像的位置并将图像粘贴到中心
        left = (target_size[0] - image.width) // 2
        top = (target_size[1] - image.height) // 2
        new_image.paste(image, (left, top))

        # 保存为BMP格式
        bmpfile = os.path.join(output_folder, os.path.splitext(os.path.basename(jpgfile))[0] + ".bmp")
        new_image.save(bmpfile, format="BMP")

if __name__ == "__main__":
    input_folder = "jpg_200"
    output_folder = "bmp_200_512_yolo"
    target_size = (512, 512)
    convert_jpg_to_bmp(input_folder, output_folder, target_size)
